"use client";

import React, { Fragment, JSX, useEffect, useRef } from "react";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { useGSAP } from "@gsap/react";
import Lenis from "lenis";
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
import classNames from "classnames";
import { useIsMobile } from "@/hooks/use-mobile";

// 注册ScrollTrigger插件
gsap.registerPlugin(ScrollTrigger);

const cards = [
  {
    title: "游🎮戏",
    content: (
      <>
        <div>爱玩各式各样的游戏</div>
        <div>竞速类、格斗类、mmo、moba、fps、单机无所不触</div>
        <div>从小爱在4399玩小游戏</div>
        <div>长大喜欢在steam玩玩各类游戏</div>
      </>
    ),
  },
  {
    title: "代⌨️码",
    content: (
      <>
        <div>爱写一些奇奇怪怪的project</div>
        <div>主要是前端JS领域，最近爱上了交互动画（其实也就用用gsap）</div>
        <div>大三开始写写代码</div>
        <div>服务端数据库会一丢丢</div>
      </>
    ),
  },
  {
    title: "工💼作",
    content: (
      <>
        <div>练习时长两年半的前端练习生（还真是）</div>
        <div>第一份在温州，实习兼首秀</div>
        <div>第二份在杭州，依旧前端小牛马</div>
      </>
    ),
  },
];

export interface CardData {
  title: string;
  content: JSX.Element;
}

const HorizontalScroll = () => {
  const isMobile = useIsMobile();
  const wrapperRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const cardsBoxRef = useRef<HTMLDivElement>(null);
  const lenisRef = useRef<Lenis | null>(null);
  const distanceRef = useRef(0);
  const ifLeaveRef = useRef(false);
  const bgRefs = useRef<(HTMLImageElement | null)[]>([]);
  const imgRefs = useRef<(HTMLDivElement | null)[]>([]);

  // 初始化Lenis平滑滚动
  useEffect(() => {
    lenisRef.current = new Lenis({
      duration: 1,
      easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
      smoothWheel: true,
      autoRaf: true,
    });

    return () => {
      lenisRef.current?.destroy();
    };
  }, []);

  // 计算距离和设置高度
  const resize = () => {
    if (cardsBoxRef.current && wrapperRef.current) {
      distanceRef.current = cardsBoxRef.current.offsetWidth - window.innerWidth;
      wrapperRef.current.style.height = `${distanceRef.current}px`;

      if (ifLeaveRef.current && cardsBoxRef.current) {
        cardsBoxRef.current.style.transform = `translateX(-${distanceRef.current}px)`;
      }
    }
  };

  useGSAP(() => {
    if (!wrapperRef.current || !cardsBoxRef.current) return;

    // 初始化时计算距离
    resize();

    // 创建ScrollTrigger
    ScrollTrigger.create({
      trigger: wrapperRef.current,
      start: "top top",
      end: "bottom bottom",
      onUpdate: (self) => {
        if (cardsBoxRef.current) {
          const distance_x = self.progress * distanceRef.current;
          cardsBoxRef.current.style.transform = `translateX(-${distance_x}px)`;
          const imgSpeed = window.screen.width > 768 ? 1.2 : 1;
          const bgSpeed = 0.5;

          // 为图片添加视差效果
          imgRefs.current.forEach((img) => {
            if (img) {
              img.style.transform = `translateX(${distance_x * imgSpeed}px)`;
            }
          });
          bgRefs.current.forEach((bg) => {
            if (bg) {
              bg.style.transform = `translateX(${distance_x * bgSpeed - 80}px)`;
            }
          });
        }
      },
      onLeave: () => {
        ifLeaveRef.current = true;
      },
      onEnterBack: () => {
        ifLeaveRef.current = false;
      },
    });

    // 监听窗口大小变化
    const handleResize = () => {
      resize();
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  const renderCards = (card: CardData, index: number) => {
    const leftStyle = `calc(${index * -100}% - ${index * 12}vw)`;

    return (
      <div className="relative shadow-xl p-10 w-[88vw] h-[70vh] rounded-[5rem] bg-gray-100 border border-gray-200 ml-[6vw] mr-[6vw] flex-shrink-0 overflow-hidden">
        <div className="relative z-10 flex flex-col items-center h-full gap-8">
          <p className="font-sans text-5xl text-gray-900 tracking-widest font-black uppercase z-10">
            {card.title}
          </p>
          <div
            className={classNames(
              "w-full text-center font-light flex flex-col gap-4",
              isMobile ? "" : "text-3xl"
            )}
          >
            {card.content}
          </div>
        </div>
        <img
          className="absolute bottom-0 opacity-50 h-full w-[350%] max-w-[none]"
          src="/img/skybg.png"
          ref={(el) => {
            bgRefs.current[index] = el;
          }}
          style={{
            left: leftStyle,
          }}
        />
        <div
          ref={(el) => {
            imgRefs.current[index] = el;
          }}
          className="absolute bottom-0 h-36"
          style={{
            left: leftStyle,
          }}
        >
          <DotLottieReact src="/lottie/purple.json" loop autoplay />
        </div>
      </div>
    );
  };

  return (
    <div ref={wrapperRef} className="relative w-full">
      <div
        ref={containerRef}
        className="sticky top-0 flex items-center w-full h-screen overflow-hidden"
      >
        <div ref={cardsBoxRef} className="flex w-max">
          {cards.map((card, index) => (
            <Fragment key={card.title}>{renderCards(card, index)}</Fragment>
          ))}
        </div>
      </div>
    </div>
  );
};

export default HorizontalScroll;
